<?php

namespace Admin\Controller;

use think\Controller;

class BaseController extends Controller
{
    public function _initialize()
    {
        if(empty(session('username'))){

           // return $this->display('/login');
           // exit();

          $loginUrl = U('login/index');
            if(IS_AJAX){
                return msg(111, $loginUrl, '登录超时');
            }

         // $this->redirect('/admin/login/');
        }

        // 检测权限
        $control = strtolower(CONTROLLER_NAME);
        $action = strtolower(ACTION_NAME);



       if(strpos($action,'api') !== false){
            //api方法不验证
       }else{
           if(empty(authCheck($control . '/' . $action))){
               if(IS_AJAX){
                   return msg(403, '', '您没有权限');
               }

               $this->error('403 您没有权限');
           }
       }


        $this->assign([
            'username' => session('username'),
            'rolename' => session('role')
        ]);

    }

    /**
     * 拼装参数成URL参数
     * @param unknown $paramlist
     * @return string
     */
    public function getUrlParam($paramlist){
        $paramStr = "";
        foreach($paramlist as $key=>$val){
            $paramStr .= $key."=".urlencode($val)."&";
        }
        return $paramStr;
    }


    /**格式化为json格式
     */
    public function formatjson($data=array()){

        $data['server_time']=time();
        $callback = $this->getGetParam("callback", null);
        if(!isset($callback)){
            header ("Content-Type:application/json; charset=utf-8;");
            echo json_encode($data);
        }else{
            header ( "Content-Type:text/html; charset=utf-8" );
            echo $callback."(".json_encode($data).")";
        }
    }
    /**格式为jsonp格式
     */
    public function formatjsonp($data=array(),$callback="config"){
        header ( "Content-Type:text/html; charset=utf-8" );
        $data['server_time']=time();
        $data['share']=true;
        echo $callback."(".json_encode($data).")";
    }

    /**获取POST参数
     */
    public function getPostParam($key,$default){
        $reqVal=$_REQUEST[$key];
        if(!isset($reqVal)&&$default != null)
            $reqVal=$default;
        return $reqVal;
    }
    /**获取GET参数
     */
    public function getGetParam($key,$default){
        $reqVal=$_REQUEST[$key];
        if(!isset($reqVal)&&$default != null)
            $reqVal=$default;
        return $reqVal;
    }
    /**
     *验证参数
     */
    public function validateParam($params){
        foreach ($params as $param){
            $val=$this->getPostParam($param,"");
            if($val==null){
                exit($param."参数不对");

            }
        }
    }
}

?>